const colors = require('colors-console')
const JSZip = require('jszip')
const path = require('path')
const fs = require('fs')
const shell = require('shelljs')

const zip = new JSZip();

const { name: distName } = require('../package.json');


function readDir(zip, dirPath) {
  // 读取dist下的根文件目录
  const files = fs.readdirSync(dirPath);
  files.forEach(fileName => {
    const fillPath = dirPath + "/" + fileName;
    console.log(fillPath)
    const file = fs.statSync(fillPath);
    // 如果是文件夹的话需要递归遍历下面的子文件
    if (file.isDirectory()) {
      const dirZip = zip.folder(fileName);
      readDir(dirZip, fillPath);
    } else {
      // 读取每个文件为buffer存到zip中
      zip.file(fileName, fs.readFileSync(fillPath));
    }
  });
}

function generateZip() {
  console.log(colors('green', '开始打zip包'))

  const sourceDir = path.join(__dirname, `../dist/`);
  const outputDir = path.join(__dirname, `../dist/${distName}.zip`);

  readDir(zip, sourceDir);
  zip.generateAsync({
    type: "nodebuffer", // 压缩类型
    compression: "DEFLATE", // 压缩算法
    compressionOptions: { // 压缩级别
      level: 9
    }
  }).then(content => {
    // 把zip包写到硬盘中，这个content现在是一段buffer
    fs.writeFileSync(outputDir, content);
    shell.exec(`rm -rf ./${distName}`)
    console.log(colors('green', '打zip包结束'))
  }).catch(e => {
    shell.exec(`rm -rf ./${distName}`)
    console.log(colors('red', '打zip包失败', e))
  });
}

// shell.mkdir('-p', `./${distName}/dist`)
// shell.exec( `cp -r ./dist/* ./${distName}/dist`)

generateZip();




